package com.huluobo.apps.view

import android.os.Environment
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.apps.AppsIntent
import com.huluobo.apps.AppsViewModel
import com.huluobo.apps.entity.AppEntity
import com.huluobo.apps.entity.AppEntityItem
import com.huluobo.lib_base.BaseApp
import com.huluobo.lib_base.HttpType
import com.huluobo.lib_base.UIState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

/**
 *  Created by LC on 2025/2/25.
 */
@Composable
fun AppsPage(navHostController: NavHostController, vm: AppsViewModel = hiltViewModel()) {
    val list = remember {
        //快照状态的list,可以根据页面的变化来改变,也是Compose形式常用的list类型
        SnapshotStateList<AppEntityItem>()
    }

    //弹出下载进度条,有可能看不见
    var isShowProgress by remember {
        mutableStateOf(false)
    }

    //弹出安装的进度条
    var launch by remember {
        mutableStateOf(false)
    }

    //进度条的当前进度
    var currentProgress by remember {
        mutableStateOf(0f)
    }

    //控制更新进度的协程
    val scope = rememberCoroutineScope()

    //Compose中的协程作用域
    LaunchedEffect(key1 = "", block = {
        //接受请求到的数据的状态
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnError -> {
                        Log.e("TagA", "获取应用程序列表失败:${it.msg}")
                    }

                    UIState.OnLoading -> {

                    }

                    is UIState.OnSuccess<*> -> {
                        if (it.type == HttpType.DEFAULT) {
                            list.addAll(it.data as AppEntity)
                        }

                        if (it.type == HttpType.DOWNLOAD) {
                            isShowProgress = false
                            ToastUtils.showLong("下载成功")
                            navHostController.popBackStack()
                        }
                    }
                }
            }
        }

        //发送请求
        vm.sendIntent(AppsIntent.GetApps)
    })

    Column(Modifier.padding(10.dp)) {
        Box(contentAlignment = Alignment.CenterStart, modifier = Modifier.padding(10.dp)) {
            Text(text = "在线应用", textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth())
            Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "", Modifier.clickable {
                navHostController.popBackStack()
            })
        }
        LazyVerticalGrid(columns = GridCells.Fixed(3), content = {
            items(list) {
                AppsItem(appEntityItem = it, vm, onClick = {
                    isShowProgress = true
                }, longClick = {
                    launch = true
                    scope.launch {
                        for (i in 1..100) {
                            currentProgress = i.toFloat() / 100
                            delay(100)
                        }
                        launch = false
                        ToastUtils.showLong("安装成功")
                    }
                })
            }
        })
        //如果进度条为true,展示圆形进度条
        if (isShowProgress) {
            CircularProgressIndicator()
        }

        //弹出安装进度条
        if (launch) {
            LinearProgressIndicator(
                progress = currentProgress,
                Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 40.dp)
            )
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun AppsItem(appEntityItem: AppEntityItem, vm: AppsViewModel, onClick: () -> Unit, longClick: () -> Unit) {

    //控制询问下载弹窗的bool
    var isShow by remember {
        mutableStateOf(false)
    }

    //获取下载文件夹
    val file = BaseApp.context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)

    Column(
        horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier
            .padding(10.dp)
            .combinedClickable(onClick = {
                isShow = true
            }, onLongClick = {
                longClick()
            })
    ) {
        AsyncImage(model = appEntityItem.appIcon, contentDescription = "", modifier = Modifier.size(40.dp))
        Text(text = appEntityItem.appName)
    }

    if (isShow) {
        AlertDialog(onDismissRequest = { isShow = false }, confirmButton = {
            TextButton(onClick = {
                vm.sendIntent(AppsIntent.DownloadApk(appEntityItem.apkUrl, File(file, appEntityItem.appName + ".apk")))
                isShow = false
                onClick()
            }) {
                Text(text = "确认")
            }
        }, dismissButton = {
            TextButton(onClick = { isShow = false }) {
                Text(text = "取消")
            }
        }, title = { Text(text = "下载提醒") }, text = {
            Text(text = "是否要下载${appEntityItem.appName}吗?")
        })
    }
}